import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;


public class UdpHandler extends Thread{
	static ArrayList<InetAddress> arraylist = new ArrayList<InetAddress>();
	static ArrayList<UdpHandler> handlerlist = new ArrayList<UdpHandler>();
	//private final static int port = 5060;
	private final static int bufsize = 4096 * 2;
	
	private DatagramSocket socket;
	
	UdpHandler temphandler;
	
	public UdpHandler(DatagramSocket socket){
		//init(port);
		this.socket = socket;
	}
	
	//private void init(int port){
		/*try {
			socket = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		System.out.println("Ready........");*/
	//}

	
	public void run(){
	    
		byte[] buf = new byte[bufsize];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		synchronized (handlerlist) {
			handlerlist.add(this);
		}
		
	    
		try{
			
			/*socket.receive(packet);
			int source = packet.getPort();
	    	InetAddress target = packet.getAddress();
	    	socket.connect(target,source);*/
		    while(true){
		    	System.out.println(socket.isConnected());
		    	socket.receive(packet);
		    	//socket.send(packet);
		    	synchronized (handlerlist) {
		    		//handlerlist.remove(this);
		    		for(int i = 0; i < handlerlist.size(); i ++){
		    			handlerlist.get(i).socket.send(packet);
		    			//System.out.print(i);
		    		}
		    		//handlerlist.add(this);
		    	}
		    }
	    } catch (IOException e) {
			e.printStackTrace();
		}
	    
	}

}
